package com.scorpio.framework.interceptor;


import com.scorpio.appuser.domain.AppUserEntity;
import com.scorpio.appuser.enums.UserStatusEnum;
import com.scorpio.appuser.service.AppUserService;
import com.scorpio.common.exception.CustomException;
import com.scorpio.constant.AppConstants;
import com.scorpio.constant.AppHttpStatus;
import com.scorpio.framework.annotation.PersonalLogin;
import com.scorpio.framework.service.impl.TokenService;
import com.scorpio.framework.service.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 个人用户登录拦截器
 */
@Component
public class PersonalAuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AppUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        PersonalLogin annotation = null;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(PersonalLogin.class);
        }
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser == null) {
            if (annotation != null) {
                throw new CustomException("请登录后操作", AppHttpStatus.UNAUTHORIZED);
            }
        } else {
            AppUserEntity user = userService.findCacheUser(loginUser.getUid());
            if (user != null) {
                if (!UserStatusEnum.Normal.getValue().equals(user.getStatus())) {
                    throw new CustomException("帐号已被封", AppHttpStatus.UNAUTHORIZED);
                }
                request.setAttribute(AppConstants.APP_LOGIN_USER_KEY, user);
            } else if (annotation != null) {
                throw new CustomException("无效用户请重新登录", AppHttpStatus.UNAUTHORIZED);
            }
        }
        if (loginUser != null) {
            tokenService.verifyToken(loginUser);
        }
        return super.preHandle(request, response, handler);
    }

}
